import SpecParser
import SpecExecutor
import SpecLogger
import SpecConfig

def params = [:]
if(args){
	args.each{
		def arr = it.split('=')
		params[arr[0]] = arr[1]
	}
}
if(params.beginDir)
	SpecConfig.props.beginDir = params.beginDir

def parseSpecItem = {paramName, item, lineList ->
	lineList = lineList.grep{it.trim()}

	// setup teardown headers params expects
	if('setup' == paramName)
		SpecParser.setup(item, lineList)
	else if('teardown' == paramName)
		SpecParser.teardown(item, lineList)
	else if('headers' == paramName)
		SpecParser.headers(item, lineList)
	else if('params' == paramName)
		SpecParser.params(item, lineList)
	else if('expects' == paramName)
		SpecParser.expects(item, lineList)
}

def parseSpec = {f ->
	def one = [:]

	def isBegin = false
	def isEnd = true

	def lines = []

	def paramName = null

	for(line in f.readLines()){
		line = line.trim()

		// comment
		if(line.startsWith(';;'))
			continue

		if(line.startsWith('# ')){
			def arr = line.split(' ')
			if(arr.size() > 2){
				one[arr[1]] = arr[2..-1].join(' ')
				continue
			}else if(arr.size() == 2){
				if(paramName){
					parseSpecItem(paramName, one[paramName], lines)
					lines.clear()
				}

				isBegin = true
				isEnd = false

				one[arr[1]] = [:]
				paramName = arr[1]
				continue
			}
		}

		if(isBegin && !isEnd)
			lines << line
	}

	one
}

def parse = {
	def specFilePat = /^suite(\d+)\_spec(\d+)\.txt$/

	def list = []

	String beginDir = SpecConfig.props.beginDir ?: './'
	new File(beginDir).eachFileRecurse{
		if(it.isFile() && it.name ==~ specFilePat){
			def one = parseSpec(it)
			def mat = it.name =~ specFilePat
			one.suite = mat[0][1]
			one.spec = mat[0][2]

			list << one
		}
	}

	list
}

def allTests = parse()
for(test in allTests){
	test.result = SpecExecutor.exe(test)
}

// junit report
if(SpecConfig.isReport()){
	def suiteList = allTests.collect{it.suite}.unique()
	for(suite in suiteList){
		def specListInSuite = allTests.grep{suite == it.suite}
		SpecLogger.report(suite, specListInSuite)
	}
}
